<template>
  <div>
    <a @click="showLogChange(appear)" type="primary" link class="bg-btn-log">
      <img src="@/assets/images/suspension/manage.png"/>
      <!-- <span style="margin-left: 7px">调试日志</span> -->
    </a>
    <div v-if="showLog" ref="textBox" class="input-box">
      <div class="textarea-container" v-for="(line, index) in logArray" :key="index">
        <span class="blue-text">{{ line.substring(0, 8) }}</span>
        <span v-text="line.substring(8)"></span>
      </div>
    </div>
  </div>
</template>
  
<script>
export default {
  name: 'webSocketModel',
  setup() {
    //动态加载css
    let cssPath="";
    let mode=localStorage.getItem("mode")
    if(mode=="dark"){
      cssPath = import("/src/assets/css/dark/index.scss");
    }else if(mode=="light"){
      cssPath = import("/src/assets/css/light/index.scss");
    }
    return {
      cssPath
    };
  },
  props: {
    sessionID: {}
  },
  data() {
    return {
      showLog: false,
      lockReconnect: false,
      webSocket: null,
      // wsUrl: "ws://192.168.2.5:8080/iat-service/websocket/",
      // 部署用

      // wsUrl: 'ws://ing-ms.tsc-microservice.192.168.129.160.nip.io/iat-service/websocket/',

      wsUrl: `ws://${import.meta.env.VITE_APP__SOCKET_PATH}`,
      // "ws://ing-ms.tsc-microservice.192.168.129.160.nip.io/iat-service/websocket/",
      // logArray: ['helloudsyfaukjsdfhjaksdfgjhkjhkjhkhklhhaskhfalskjdf', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi', 'hello', 'hi',],
      logArray: [],
      // 用于格式化小时，分钟，秒钟的函数
      formatTime: (time) => {
        return time < 10 ? '0' + time : time
      }
    }
  },
  computed: {
    logText() {
      return this.logArray.join('\n')
    }
  },
  mounted() {
    // this.wsUrl = this.wsUrl + this.sessionID
    // console.log('地址' + this.wsUrl)
    // this.createWebSocket(this.wsUrl)
  },
  methods: {
    currentTime() {
      const now = new Date()
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      const seconds = now.getSeconds().toString().padStart(2, '0')

      return `${hours}:${minutes}:${seconds}`
    },
    createWebSocket(url) {
      console.log('开始连接')
      try {
        if ('WebSocket' in window) {
          this.webSocket = new WebSocket(url)
          this.webSocket.onopen = () => {
            console.log('连接成功')
            this.heartCheck()
          }
          this.webSocket.onmessage = (evt) => {
            // this.heartCheck();
            //   this.appendLog(evt.data);
            console.log(evt.data)
            if (evt.data != 'ping') {
              var str = this.currentTime() + evt.data
              this.logArray.push(str)
              this.changeScrollTop()
            }
            console.log(evt)
          }
          this.webSocket.onerror = () => {
            this.reconnect(url)
          }
          this.webSocket.onclose = () => {
            this.reconnect(url)
          }
        } else {
          console.log('当前浏览器不支持WebSocket')
        }
      } catch (e) {
        console.log('连接失败')
        this.reconnect(url)
      }
    },
    reconnect(url) {
      if (this.lockReconnect) return
      this.lockReconnect = true
      console.log('正在尝试重连')
      setTimeout(() => {
        this.createWebSocket(url)
        this.lockReconnect = false
      }, 30000)
    },
    heartCheck() {
      // 0表示连接还没有建立，正在连接中 1表示连接已经建立，可以进行通信。2表示连接正在关闭。3表示连接已经关闭，或者根本没有建立。
      this.pingPong = {
        interval: null,
        maxCount: 4,
        currentCount: 0
      }
      this.pingPong.interval = setInterval(() => {
        console.log('心跳')
        if (this.webSocket.readyState === 1) {
          this.webSocket.send('ping')
          this.pingPong.currentCount = 0
        } else {
          this.pingPong.currentCount++
          if (this.pingPong.currentCount > this.pingPong.maxCount) {
            clearInterval(this.pingPong.interval)
            this.reconnect(url)
          }
        }
      }, 50000)
    },
    showLogChange() {
      this.showLog = !this.showLog
      if (this.showLog) {
        this.changeScrollTop()
        this.wsUrl = this.wsUrl + this.sessionID
        console.log('地址' + this.wsUrl)
        this.createWebSocket(this.wsUrl)
      }else {
        this.webSocket.close()
      }
      this.$emit('appear')
    },
    changeScrollTop() {
      if (this.$refs.textBox) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.textBox.scrollTop = this.$refs.textBox.scrollHeight
          }, 100)
        })
      }
    }
  },
  beforeDestroy() {
    this.webSocket.close()
  }
}
</script>
  
<style>

.input-box {
  border-top: 5px solid #fff;
  position: fixed;
  top: 80%;
  right: 50%;
  width: 100%;
  height: 20%;
  /* border-radius: 10px; */
  padding: 5px;
  z-index: 99;
  background-color: rgba(7, 7, 7, 0.861);
  transform: translateX(50%);
  overflow-y: scroll;
}

.textarea-container {
  width: 100%;
  height: auto;
  word-wrap: break-word;
  /* overflow-y: scroll; */
}

/* .log-textarea {
    width: 100%;
    height: 100%;
    resize: none;
    overflow: scroll;
} */
.blue-text {
  color: red;
}
</style>